<?php
 
namespace Home\Controller;
use Think\Controller;
/*
 * 全局控制器
 * */
class BaseController extends Controller { 
    /**
     * 前台控制器初始化
     */
	public $opensession =array();
	public $dbprefix=""; 
	public $wxconfig=array();
	
    protected function _initialize(){ 
    	ob_clean();
    	$this->dbprefix=C('DB_PREFIX');
    	//判断是否获取当前微信用户的基本信息
    	$this->wxconfig =$this->getwxconfig();
		
	if(session("openid")){ 
    		$this->opensession= (array)session("openid"); 
    		if(empty($this->opensession['openid']))
    		{
    			unset($this->opensession); 
    		} 
    	}
    	else{
            $openid="ok2DgvtNdo31VJhKF69CsVHrLqdU";
            if($_COOKIE[C('COOKIE_PREFIX').'openidCookie'])
          {
            //删除cookie
            cookie ("openidCookie", "", time() - 3600);
          }
        $cookieName="openidCookie";
        $cookieValue['openidCookie']=base64_encode("51M@".$openid."@".C("KEY"));
        cookie($cookieName,json_encode($cookieValue), C("COOKIE_TIME"));

			$this->brandUser();
       
    	    $this->opensession= (array)session("openid");
            
		    //if($_cookie['userCookie'])
				
				//删除cookie
			// setcookie ("userCookie", "", time() - 3600);
		}
 
       
 /*       $sd=array();
        $url = C("WEBURL").'/wx.php/Offer/user_offer/offerid/0657E25B-7969-CEFA-9523-52740C5EF668';
        $sd['touser']='ok2Dgvorz_g_GMqrfRBSN8U5eKVE';
        $sd['msgtype']='text';
        $sd['text']['content']= urlencode("<a href='".$url."'>我们的管理员已经审核了您的报价单，请点击该连接查看</a>");

		$this->SendMessage($sd);*/
    	
    	
    	
    	//订阅号不能在访问的时候获取微信用户信息
       /*
    	if(session("openid")){
			
    		$this->opensession= (array)session("openid"); 
    		if(empty($this->opensession['openid']))
    		{
    			unset($_SESSION["openid"]); 
    		} 
    	}
    	else{
    		//如果也不带参数，第一次访问授权
    		$code = $_GET['code'];  
    		//是否获取到微信帐号信息
    		if($code){
    			$this->getwxopenid();
    			$this->opensession= (array)session("openid");
    		}
    	/*	
    		 //测试状态构建session 
    		if(APP_DEBUG){ 
    			$open=array();
    			$open['wxconfig']=$this->wxconfig;
    			$open['openid']="ok2DgvtNdo31VJhKF69CsVHrLqdU";
    			$open['nickename']="水";
    			session('openid', $open);
    			$this->opensession= (array)session("openid");
    		} 
    	} */
    } 
    
   
    //判断是否登录
   public function  isLogin(){
	   	//判断是否登录
	   	if (!is_array($this->opensession['user'])||empty($this->opensession['user']['user_id'])) {
	   		$this->redirect("Login/login");
	   		exit;
	   	}
   }
     
    
    //验证签名
    public function valid($ary){
    	$echoStr = isset($_GET["echostr"])?$_GET["echostr"]:$_POST['echostr'];
    	$signature = isset($_GET["signature"])?$_GET["signature"]:$_POST['signature']; //$_GET["signature"];
    	$timestamp = isset($_GET["timestamp"])?$_GET["timestamp"]:$_POST['timestamp']; //$_GET["timestamp"];
    	$nonce = isset($_GET["nonce"])?$_GET["nonce"]:$_POST['nonce']; //$_GET["nonce"];
    	$token = $ary['token']; //是开发应用设置的token值
    	$tmpArr = array($token, $timestamp, $nonce);
    	sort($tmpArr,SORT_STRING);
    	$tmpStr = implode($tmpArr);
    	$tmpStr = sha1($tmpStr);
    
    	 //$ret=array('str'=>$tmpStr,'c'=>$signature,'s'=>$tmpArr,'o'=>$echoStr);
    	 //$this->logger("验证".json_encode($ret));
    
    	if($tmpStr == $signature){
    		echo $echoStr;
    		exit;
    	}
    }
    
    //响应消息
    public function responseMsg() {
    	$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
    	if (empty($postStr)){
    		echo "";
    		exit;
    	}
    
    	//$this->logger("接受数据：".$postStr);
    
    	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
		
		//构建openid cookie
		$openid=trim($object->ToUserName);
		if($_COOKIE[C('COOKIE_PREFIX').'openidCookie'])
		{
			//删除cookie
	        cookie ("openidCookie", "", time() - 3600);
		}
		$cookieName="openidCookie";
	    $cookieValue['openidCookie']=base64_encode("51M@".$openid."@".C("KEY"));
	    cookie($cookieName,json_encode($cookieValue), C("COOKIE_TIME"));
		
    	$RX_TYPE = strtolower(trim($postObj->MsgType));
    
    	 //$this->logger("事件：".$RX_TYPE); 
    	 //$this->logger("内容：".trim($postObj->Content));
    	//消息类型分离
    	switch ($RX_TYPE)
    	{
    		case "event":
    			$result = $this->receiveEvent($postObj);
    			break;
    		case "text":
    			$result = $this->receiveText($postObj);
    			break;
    		case "link":
    			$result = $this->receiveLink($postObj);
    			break;
    		case "image":
    			//$result = $this->transmitZhuan($postObj);
    			$result = $this->receiveImage($postObj);
    			break;
    		case "video":
    			//$result = $this->transmitZhuan($postObj);
    			$result = $this->receiveVideo($postObj);
    			break;
    		case "voice":
    			//$result = $this->transmitZhuan($postObj);
    			$result = $this->receiveVoice($postObj);
    			break;
    		default:
    			$result = $this->receiveText($postObj);
    			//$result = "unknown msg type: ".$RX_TYPE;
    			break;
    	}
    
    	 //$this->logger($RX_TYPE."_".$postObj->Event.":".$result);
    	echo $result;
    	exit; 
    		
    	//return $this->transmitZhuan($postObj);
    }
    
    //接收事件消息
    private function receiveEvent($object)
    { 
    	$type = $object->Event;
    	if ($type == 'subscribe') {
    		$rsw=M("wx_reply")->where("keyword='subscribe'")->find();
    		//关注回复
    		$text= $rsw['description'];
    		$text= empty($text)?'欢迎关注 '.$rsw['title'].'微信公众号':$text;
    			
    		$result = $this->transmitText($object, $text);
    			
    	} else if ($type == 'CLICK') {
    		//自定义菜单点击事件
    		$key = $object->EventKey; 
    		$rs=M("wx_reply")->where("`keyword`='".$key."'")->order("replyid desc")->select();
    		if($rs){
    			$arymsg=array();
    			foreach($rs as$k=>$v){
    				$url=$v['url'];
    				if(!empty($url) && strpos(strtolower($url),"http")===false && strpos(strtolower($url),"services/")!==false)
    				{
    					$url=C("WEBURL").C("WXConfigPathUrl")."/".$v['url'];
    					$v['url']=$url;
    				}
    				$arymsg[]=$v;
    			}
    			$result = $this->transmitNews($object, $arymsg);
    		}
    	}else{
    		$text='欢迎关注！';
    		$result = $this->transmitText($object, $text);
    	}
    	return $result;
    }
    
     
    //接收文本消息
    private function receiveText($object)
    {
    	$keyword = trim($object->Content);
    	$rs=M("wx_reply")->where("`keyword`='".$keyword."'")->find();
    	//$this->logger("用户发送内容： key='".$keyword."'");
    	if($rs){
    		$url=$rs['url'];
    		if(!empty($url) && strpos(strtolower($url),"http")===false && strpos(strtolower($url),"services/")!==false)
    		{
    			$url=C("WEBURL").C("WXConfigPathUrl")."/".$v['url'];
    		}
    		if($rs['type']==0)
    		{
    			$sendmsg['url']=$url;
    			$sendmsg['title']=$rs['title'];
    			$sendmsg['imgurl']=$rs['picurl'];
    			$sendmsg['content']=$rs['description'];
    			$ret=$this->transmitNews($object, $sendmsg);
    		}
    		else
    		{
    			//$sendmsg=  $rs['title']."\n".$rs['description'];
    			$sendmsg=(!empty($url)?"<a href='".$url."'>".$rs['title']."</a>"."\n".$rs['description']:$rs['title']."\n".$rs['description']);
    			$ret=$this->transmitText($object, $sendmsg);
    		}
    		return $ret;
    	}
    	else
    	{
    		 // $this->logger("用户发送内容：查询结果为空");
    		$ret = $this->transmitText($object, "欢迎光临51M供应链平台。您是我们的天使。您的客户是我们共同的上帝。我们将尽我们所能给您带来最好的服务。如需客服咨询请加微信61426666080或电话咨询+61426666080");
    		return $ret;
    	}
    } 
    
    //接收图片消息
    private function receiveImage($object)
    {
    	$content = array("MediaId"=>$object->MediaId);
    	$result = $this->transmitImage($object, $content);
    	return $result;
    }
    
    //接收位置消息
    private function receiveLocation($object)
    {
    	$content = "你发送的是位置，纬度为：".$object->Location_X."；经度为：".$object->Location_Y."；缩放级别为：".$object->Scale."；位置为：".$object->Label;
    	$result = $this->transmitText($object, $content);
    	return $result;
    }
    
    //接收语音消息
    private function receiveVoice($object)
    {
    	if (isset($object->Recognition) && !empty($object->Recognition)){
    		$content = "你刚才说的是：".$object->Recognition;
    		$result = $this->transmitText($object, $content);
    	}else{
    		$content = array("MediaId"=>$object->MediaId);
    		$result = $this->transmitVoice($object, $content);
    	}
    
    	return $result;
    }
    
    //接收视频消息
    private function receiveVideo($object)
    {
    	$content = array("MediaId"=>$object->MediaId, "ThumbMediaId"=>$object->ThumbMediaId, "Title"=>"", "Description"=>"");
    	$result = $this->transmitVideo($object, $content);
    	return $result;
    }
    
    //接收链接消息
    private function receiveLink($object)
    {
    	$content = "你发送的是链接，标题为：".$object->Title."；内容为：".$object->Description."；链接地址为：".$object->Url;
    	$result = $this->transmitText($object, $content);
    	return $result;
    }
    
    //回复文本消息
    private function transmitText($object, $content)
    {
    	$xmlTpl = "<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[text]]></MsgType>
		<Content><![CDATA[%s]]></Content>
		</xml>";
    	$result = sprintf($xmlTpl, trim($object->FromUserName), trim($object->ToUserName), time(), trim($content));
    	return $result;
    }
    
    
    private function transmitTextzidong ($object, $content)
    {
    	$xmlTpl = "<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[text]]></MsgType>
		<Content><![CDATA[%s]]></Content>
		</xml>";
    	$result = sprintf($xmlTpl, $object['FromUserName'], $object['ToUserName'], time(), $content);
    	return $result;
    }
    
    
    //回复图片消息
    private function transmitImage($object, $imageArray)
    {
    	$itemTpl = "<Image>
	    <MediaId><![CDATA[%s]]></MediaId>
		</Image>";
    
    	$item_str = sprintf($itemTpl, $imageArray['MediaId']);
    
    	$xmlTpl = "<xml>
    	<ToUserName><![CDATA[%s]]></ToUserName>
    	<FromUserName><![CDATA[%s]]></FromUserName>
    	<CreateTime>%s</CreateTime>
    	<MsgType><![CDATA[image]]></MsgType>
    	$item_str
    	</xml>";
    
    	$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
    	return $result;
    }
    
    //回复语音消息
    private function transmitVoice($object, $voiceArray)
    {
    	$itemTpl = "<Voice>
	    <MediaId><![CDATA[%s]]></MediaId>
		</Voice>";
    
    	$item_str = sprintf($itemTpl, $voiceArray['MediaId']);
    
    	$xmlTpl = "<xml>
    	<ToUserName><![CDATA[%s]]></ToUserName>
    	<FromUserName><![CDATA[%s]]></FromUserName>
    	<CreateTime>%s</CreateTime>
    	<MsgType><![CDATA[voice]]></MsgType>
    	$item_str
    	</xml>";
    
    	$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
    	return $result;
    }
    
    //回复视频消息
    private function transmitVideo($object, $videoArray)
    {
    	$itemTpl = "<Video>
	    <MediaId><![CDATA[%s]]></MediaId>
	    <ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
	    <Title><![CDATA[%s]]></Title>
	    <Description><![CDATA[%s]]></Description>
		</Video>";
    
    	$item_str = sprintf($itemTpl, $videoArray['MediaId'], $videoArray['ThumbMediaId'], $videoArray['Title'], $videoArray['Description']);
    
    	$xmlTpl = "<xml>
    	<ToUserName><![CDATA[%s]]></ToUserName>
    	<FromUserName><![CDATA[%s]]></FromUserName>
    	<CreateTime>%s</CreateTime>
    	<MsgType><![CDATA[video]]></MsgType>
    	$item_str
    	</xml>";
    
    	$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
    	return $result;
    }
    
    //回复图文消息
    private function transmitNews($object, $newsArray)
    {
    	if(!is_array($newsArray)){
    		return;
    	}
    	$item_str = "";
    	foreach ($newsArray as $key=> $item){
    		$item['PicUrl']=C('WEBURL')."/Public/Uploads/".$item['imgurl'];
    		$item_str.= "<item>
	        <Title><![CDATA[".$item['title']."]]></Title>
	        <Description><![CDATA[".$item['content']."]]></Description>
	        <PicUrl><![CDATA[".$item['PicUrl']."]]></PicUrl>
	        <Url><![CDATA[".$item['url']."]]></Url>
	    	</item>";
    	}
    
    	$xmlTpl = "<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[news]]></MsgType>
		<ArticleCount>%s</ArticleCount>
		<Articles>".$item_str."</Articles>
		</xml>";
    
    	$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
    	return $result;
    }
    
    //回复音乐消息
    private function transmitMusic($object, $musicArray)
    {
    	$itemTpl = "<Music>
	    <Title><![CDATA[%s]]></Title>
	    <Description><![CDATA[%s]]></Description>
	    <MusicUrl><![CDATA[%s]]></MusicUrl>
	    <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
		</Music>";
    
    	$item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);
    
    	$xmlTpl = "<xml>
    	<ToUserName><![CDATA[%s]]></ToUserName>
    	<FromUserName><![CDATA[%s]]></FromUserName>
    	<CreateTime>%s</CreateTime>
    	<MsgType><![CDATA[music]]></MsgType>
    	$item_str
    	</xml>";
    
    	$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
    	return $result;
    }
    
    //回复多客服消息
    private function transmitService($object)
    {
    	$xmlTpl = "<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[transfer_customer_service]]></MsgType>
		</xml>";
    	$result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
    	return $result;
    }
    
    //自动接入客服
    public function transmitZhuan ($object) {
    	 
    	//随机获取访客列表客服
    	$kefus=M('kf')->where(array('sort'=>1))->select();
    	$key=array_rand($kefus);
    	$kf_account=trim($kefus[$key]['username']);
    	$xmlTpl = "<xml>
		<ToUserName><![CDATA[%s]]></ToUserName>
		<FromUserName><![CDATA[%s]]></FromUserName>
		<CreateTime>%s</CreateTime>
		<MsgType><![CDATA[transfer_customer_service]]></MsgType>
		 <TransInfo>
		         <KfAccount><![CDATA[%s]]></KfAccount>
		  </TransInfo>
		</xml>";
    	$result = sprintf($xmlTpl,trim($object->FromUserName),trim($object->ToUserName),time(),$kf_account);
    	return $result;
    }
    
    // ==== 通用方法  ===
    
    //发消息
    public function MessageSend($openId,$type,$content) {
    	$data['touser'] = $openId;
    	$data['msgtype'] = $type;
    	$data[$type] =$content;
    	$json =urldecode(json_encode($data));
    	$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$this->Access_Token();
    	$res = $this->http_request($url,$json);
    	$result = json_decode($res, true);
    	return $result;
    }
    /* 
     //文本信息发送，其他信息格式参看接口说明
     $data=array('touser'=>openid,'msgtype'=>text,text=>array('content'=>'发送内容，可以带连接标签'));
     */
    public function SendMessage($data=array()) {
    	$json = urldecode(json_encode($data));
    	$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$this->Access_Token();
    	$res = $this->http_request($url,$json);
    	$result = json_decode($res, true);
    	return $result;
    }
    
    
    //获取临时素材
    public function get_media ($media_id) {
    	$url = "https://api.weixin.qq.com/cgi-bin/media/get?access_token=".$this->Access_Token().'&media_id='.$media_id;
    	$result = $this->http_request($url);
    	return $result;
    }
    //获取永久素材
    public function get_material ($media_id) {
    	$data['media_id'] = $media_id;
    	$json = json_encode($data);
    	$url = "https://api.weixin.qq.com/cgi-bin/material/get_material?access_token=".$this->Access_Token();
    	$res = $this->http_request($url,$json);
    	$result = json_decode($res, true);
    	return $result;
    }
    //获取永久素材列表
    public function get_materiallist() {
    	$data['type'] = 'news';//素材的类型，图片（image）、视频（video）、语音 （voice）、图文（news）
    	$data['offset'] = 0;
    	$data['count'] = 20;
    	$json = json_encode($data);
    	$url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=".$this->Access_Token();
    	$res = $this->http_request($url,$json);
    	$result = json_decode($res, true);
    	return $result;
    }
    
    //====================================针对发送信息，关键字处理=========================
    
    //发送指定发送信息到微信
    public function keywordsend ($openid,$msg) {
    	$url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".$this->Access_Token();
    	$data['touser'] = $openid;
    	$data['msgtype'] = 'text';
    	$text = urlencode($msg);
    	$data['text'] = array('content'=>$text);
    	$rtu = urldecode(json_encode($data));
    	return $this->http_request($url,$rtu);
    }
    
    //==========================================关键字处理方法完成========================================
      
    //得到access_token，并判断时间以及更新数据库
    public function Access_Token () {
    	$cache_wxtoken= APP_PATH."/Runtime/Data/authorization_Token.php";
    	$rows=array();
    	$flag=0;
    	if(file_exists($cache_wxtoken))
    	{
    		include $cache_wxtoken;
    		$ret= json_decode($json,true);
    		$date = $ret['addtime'] + 7200;
    		if (time() >= $date) {
    			$flag=1;
    		}
    		else
    		{
    			$token=$ret['Token'];
    		}
    	}
    	else
    	{
    		$flag=1;
    	}
    
    	if($flag){
    		$token=$this->GetToken();
    		$keyword="$"."json='".urldecode("{\"Token\":\"".$token."\",\"addtime\":\"".time()."\"}")."';";
    		buildCache($cache_wxtoken,$keyword);
    	}
    	return $token;
    }
     
    /**
     * [PostAt 获取Access_toke]
     */
    public function GetToken () { 
    	$wxconfig= $this->getwxconfig(); 
    	$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$wxconfig['appid']."&secret=".$wxconfig['appsecret'];
    	$res = $this->http_request($url);
    	$result = json_decode($res, true);
    	return $result["access_token"];
    }
    
    //获取微信配置信息
    public function getwxconfig(){  
    	$config=array(); 
    	$config['appid']=C("APPID");
    	$config['appsecret']=C("APPSecret");
    	$config['token']=C("SetUrlTOKEN"); 
    	$config['encodingaeskey']=C("encodingaeskey");
    	return $config;
    }
    
    //获取当前用户进入公众号 得到的openid,openid_nickenme
    public function getwxopenid()
    {
    	$code = $_GET['code'];
    	if($code){ 
    		$wxconfig= $this->getwxconfig();
    		$url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$wxconfig['appid']."&secret=".$wxconfig['appsecret']."&code=".$code."&grant_type=authorization_code";
    		$data = $this->http_request($url);
    		$data = json_decode($data,true);
    		if(array_key_exists('errcode',$data))exit;
    
    		$open=array();
    		$open['wxconfig']=$wxconfig;
    		$open['openid']=$data['openid'];
    
    		$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$this->Access_Token()."&openid=".$data['openid']."&lang=zh_CN";
    		$ret = $this->http_request($url);
    		$ret = json_decode($ret,true);
    		if(array_key_exists('errcode',$ret))exit;
    		$open['nickename']=$ret['nickname']; 
    		
    		//绑定用户自动登录,绑定用户信息，已存在用户在微信登录 或者 用户从微信注册时绑定操作
    		$user= M("users")->field("a.*")->alias("a")->join("inner join ".$this->dbprefix."wx_binduser as b on a.user_id=b.user_id")->where("b.bindtype='user' and b.openid='".$data['openid']."'")->find();
            if($user){
            	$open['user']=$user;
            }  
            session('openid', $open);
            //
    		//对用户信息进行处理
    		$dao=M("wx_openuser");    		
    		$rs=$dao->where(array('openid'=>$data['openid']))->order("createtime asc")->select();
    		if(!$rs)
    		{ 
    			$ret['createtime']=date("Y-m-d H:i:s");
    			$rid=$dao->add($ret); 
    			//保存用户会员注册信息 
    		}
    		else
    		{
    			/* //多条微信用户记录，过滤删除保留一条
    			$ids=$lid="";
    			if(count($rs)>1)
    			{
    				foreach($rs as $k=>$v)
    				{
    					if(empty($ids)){
    						$lid =$v['id'];
    						continue;
    					}
    					$ids.= ((empty($ids)?"":",").$v['id']);
    				}
    				if(!empty($ids))
    				{
    					//$dao->where("id in($ids)")->delete();
    					//M("member")->where("operuserid in($ids)")->delete();
    				}
    			}
    			*/
    			$ret['openid']=$data['openid']; 
    			$dao->save($ret);
    		}
    	}
    }
	
	public function brandUser(){ 
		
		    $wxconfig= $this->getwxconfig();
    		  
    		$open=array();
    		$open['wxconfig']=$wxconfig;
	
			if(!$_COOKIE[C('COOKIE_PREFIX').'userCookie'] || !$_COOKIE[C('COOKIE_PREFIX').'openidCookie'])
			{

				return ;
			}

			$userCookie=json_decode($_COOKIE[C('COOKIE_PREFIX')."userCookie"],true);
		    $userCookie=base64_decode($userCookie['userCookie']);
		    $userid=explode("@",$userCookie);
			$openidCookie=json_decode($_COOKIE[C('COOKIE_PREFIX').'openidCookie'],true);
			$openidCookie=base64_decode($openidCookie['openidCookie']);
			$openid=explode("@",$openidCookie);

			if($userid[0] != "51M")
			{       
					return ;
			}
		    if($openid[0] != "51M")
			{
					return ;
			}
			$result=M("Users")->where("user_id = ".$userid[1])->find();

			if(!$result)
			{
				return ;
			}

			$brindid=M("wx_binduser")->where("(user_id = ".$userid[1]." or openid = '".$openid[1]."') and bindtype='user'")->find();
			if(!$brindid)
			{
				$data['wx_id']=getGuid();
                $data['user_id']=$userid[1];
                $data['openid']=$openid[1];
                $data['bindtype']="user";
                $data['createtime']=date("Y-m-d H:i:s");
                M("wx_binduser")->add($data);
			}

    		$open['userid']=$userid[1];
    		$open['openid']=$openid[1];

    		$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$this->Access_Token()."&openid=".$openid[1]."&lang=zh_CN";


    		$ret = $this->http_request($url);

    		$ret = json_decode($ret,true);
    		if(array_key_exists('errcode',$ret))exit;
    		//$open['nickename']=$ret['nickname']; 
			$ret['createtime']=date("Y-m-d H:i:s");

    		//查询wx_openuser 更新或添加用户
			$result=M("wx_openuser")->where("openid = '".$ret['openid']."'")->field('nickname,headimgurl')->find();
			//存在则更新
			if($result)
			{
				if($result['nickname'] != $ret['nickname'] || $result['headimgurl'] != $ret['headimgurl'])
				{
					//$data['nickname']=$ret['nickname'];
					//$data['headimgurl']=$ret['headimgurl'];
					M("wx_openuser")->where("openid = '".$ret['openid']."'")->save($ret);
				}
			}
			//不存在添加
			else
			{
				M("wx_openuser")->add($ret);
			}
    		//绑定用户自动登录,绑定用户信息，已存在用户在微信登录 或者 用户从微信注册时绑定操作
    		$user= M("users")->field("a.*")->alias("a")->join("inner join ".$this->dbprefix."wx_binduser as b on a.user_id=b.user_id")->where("b.bindtype='user' and b.openid='".$openid[1]."'")->find();
            if($user){
            	$open['useropen']=array_merge($user,$ret);
            }  
            session('openid',$open);
      
		
	}
     
    //HTTP请求（支持HTTP/HTTPS，支持GET/POST）
    protected function http_request($url, $data = null){
    	$curl = curl_init();
    	curl_setopt($curl, CURLOPT_URL, $url);
    	curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    	curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    	if (!empty($data)){
    		curl_setopt($curl, CURLOPT_POST, 1);
    		curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    	}
    	curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    	$output = curl_exec($curl);
    	curl_close($curl);
    	return $output;
    }
    
    
    //日志记录
    protected function logger($log_content)
    {
    	if(isset($_SERVER['HTTP_APPNAME'])){   //SAE
    		sae_set_display_errors(false);
    		sae_debug($log_content);
    		sae_set_display_errors(true);
    	}else if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL
    		$max_size = 10000;
    		$log_filename = "log.xml";
    		$dir         =  dirname($log_filename);
    		if(!is_dir($dir)){
    			mkdir($dir,0777,true);
    		}
    		if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
    		file_put_contents($log_filename, date('H:i:s')." ".$log_content."\r\n", FILE_APPEND);
    	}
    }
    
    
    
    protected function getuserlistbywxcode()
    {
    	$wxconfig=$this->getwxconfig();
    	$access_token=$this->Access_Token();
    	$url="https://api.weixin.qq.com/cgi-bin/user/get?access_token=$access_token&next_openid=";
    	$ret = $this->http_request($url);
    	$ret = json_decode($ret,true);
    	if(array_key_exists('errcode',$ret))exit;
    	$ary=$ret['data']['openid'];
    
    	foreach($ary as $v)
    	{
    		if(empty($v))continue;
    
    		$url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$access_token."&openid=".$v."&lang=zh_CN";
    		$ret =  $this->http_request($url);
    		$ret = json_decode($ret,true);
    		if(array_key_exists('errcode',$ret))continue;
    		//$open['nickename']=$ret['nickname'];
    
    		//对用户信息进行处理
    		$dao=M("wx_openuser");
    		$rs=$dao->where(array('openid'=>$v))->order("openid asc")->select();
    		if(!$rs)
    		{  
    			$ret['createtime']=date("Y-m-d H:i:s");
    			$rid=$dao->add($ret); 
    		}
    		else
    		{
    			/*
    			$ids=$lid="";
    			if(count($rs)>1)
    			{
    				foreach($rs as $k=>$v)
    				{
    					if(empty($ids)){
    						$lid =$v['id'];
    						continue;
    					}
    					$ids.= ((empty($ids)?"":",").$v['id']);
    				}
    				if(!empty($ids))
    				{
    					$dao->where("id in($ids)")->delete();
    					M("member")->where("operuserid in($ids)")->delete();
    				}
    			}
    			*/
    			$ret['openid']=$v; 
    			$dao->save($ret);
    		}
    	}
    }
    
       
    /**
     * 生成链接URL
     * @param  integer $page 页码
     * @return string
     */
    private function url($page){
    	if(empty($page)){
    		return 'javascript:;';
    	}
    	$_query_data=(array)I('request.');
    	$_query_data['p']=$page;
    	return U(ACTION_NAME, $_query_data);
    }
    
}